package com.teufandsub.socialproximity.controller;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;

import org.json.JSONObject;

import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;

public class Utils {

	public static String toMD5(String passwd){
		String password = passwd;
		
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(password.getBytes());
			
			byte byteData[] = md.digest();
			
	        StringBuffer sb = new StringBuffer();	        
	        for (int i = 0; i < byteData.length; i++) {
	        	sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
	        }
	        
	        password = sb.toString();
		} catch (Exception e) {
			Log.e(Constants.APP_NAME, "MD5 conversion problem : " + e.toString());
		}
		
		
		return password;
	}
	
    public static boolean hasConnectivity(Context context){
    	ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    	if(cm.getActiveNetworkInfo()==null){
    		return false;
    	}else{
    		return cm.getActiveNetworkInfo().isAvailable();
    	}  	
    }
	
	public static JSONObject readResponse(InputStream is) {
	    String line = "";
	    StringBuilder total = new StringBuilder();

	    BufferedReader rd = new BufferedReader(new InputStreamReader(is));

	    try {
		    while ((line = rd.readLine()) != null) { 
		        total.append(line).append("\n"); 
		    }
		} catch (Exception e) {
			Log.e(Constants.APP_NAME, "Unable to convert HTTPResponse : " + e.toString());
		}
	    JSONObject response = null;
	    try {
	    	response = new JSONObject(total.toString());  	
		} catch (Exception e) {
			Log.e(Constants.APP_NAME, "Unable to convert to JSONObject : " + e.toString());
		}
	    
	    return response;
	}
}
